package com.alibaba.citrus.ots.platform.enhance.functions.diff.common.router;

import com.alibaba.citrus.ots.platform.enhance.facade.service.diff.common.DiffCheckRequest;
import com.alibaba.citrus.ots.platform.enhance.functions.diff.common.template.OneDiffOneTemplate;
import com.alibaba.citrus.ots.platform.enhance.repository.model.diff.common.FieldCheckFailDTO;
import com.alibaba.citrus.ots.platform.enhance.repository.model.diff.common.FieldLineDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author: qiaojiange
 * @create: 2022/01/19
 * @Description 对账处理器
 */
public abstract class DiffCheckProcessor {
    /**
     * 获取策略路由
     *
     * @return
     */
    public abstract String obtainStrategyRoute();

    /**
     * 对账自定义实现方案
     *
     * @param diffCheckRequest 对账请求
     * @return 对账结果
     */
    public abstract Result<String> diff(DiffCheckRequest diffCheckRequest);

    /**
     * 对账
     *
     * @param diffCheckRequest 对账请求
     * @return 对账结果
     */
    public Result<String> diff(DiffCheckRequest diffCheckRequest, OneDiffOneTemplate oneDiffOneTemplate) {
        //这里单独的使用每一个字段进行对账
        Map<String, FieldLineDTO> baseLineDataMap = diffCheckRequest.getBaseLineDataMap();
        Map<String, FieldLineDTO> diffDataMap = diffCheckRequest.getDiffDataMap();

        //忽略列表字段
        Set<String> ignoreFields = diffCheckRequest.getIgnoreField();

        List<FieldCheckFailDTO> checkFailDTOList = new ArrayList<>();
        if (MapUtils.isNotEmpty(baseLineDataMap)) {
            for (Map.Entry<String, FieldLineDTO> entry : baseLineDataMap.entrySet()) {

                //不校验忽略的字段
                String standardDirectoryField = entry.getKey();
                if (CollectionUtils.isNotEmpty(ignoreFields) && ignoreFields.contains(standardDirectoryField)) {
                    continue;
                }

                FieldLineDTO baseLineFieldLineDto = entry.getValue();
                FieldLineDTO lineDTO = diffDataMap.get(standardDirectoryField);
                Result<String> diffResult = oneDiffOneTemplate.diff(baseLineFieldLineDto, lineDTO);
                if (diffResult.isSuccess()) {
                    continue;
                } else {
                    FieldCheckFailDTO checkFailDTO = FieldCheckFailDTO.of(baseLineFieldLineDto.getOriginFieldName(), diffResult.getMessage());
                    checkFailDTOList.add(checkFailDTO);
                }
            }
            if (CollectionUtils.isEmpty(checkFailDTOList)) {
                return Result.success("对账成功");
            }
        }

        if(CollectionUtils.isEmpty(checkFailDTOList)){
           return Result.success("对账成功");
        }
        return Result.fail("", "对账失败！明细：" + JSON.toJSONString(checkFailDTOList));
    }
}
